package service

import (
	"context"
	"errors"
	"fmt"
	"math/rand"
	"strconv"
	"time"
	"user_srv/basic/appConfig"
	__ "user_srv/basic/proto"
	"user_srv/handler/models"
	"user_srv/pkg"
)

// server is used to implement helloworld.GreeterServer.
type Server struct {
	__.UnimplementedUserServer
}

// SayHello implements helloworld.GreeterServer
func (s *Server) SayHello(_ context.Context, in *__.SendSmsReq) (*__.SendSmsResp, error) {
	code := rand.Intn(900000) + 100000

	sms, err := pkg.SendSms(in.Mobile, strconv.Itoa(code))
	if err != nil {
		return nil, err
	}
	if *sms.Body.Code != "OK" {
		return nil, fmt.Errorf("验证码格式错误")
	}

	appConfig.Rdb.Set(appConfig.Ctx, "sendSms"+in.Mobile, code, time.Minute*5)

	return &__.SendSmsResp{
		Msg: "密码发送成功",
	}, nil
}

func (s *Server) Register(_ context.Context, in *__.RegisterReq) (*__.RegisterResp, error) {
	var err error
	var u models.User

	if err = u.GetUserByMobile(appConfig.DB, in.Mobile); err != nil {
		return nil, errors.New("用户信息获取失败！")
	}
	if u.ID == 0 {
		u.Mobile = in.Mobile
		u.Account = in.Account
		result, _ := appConfig.Rdb.Get(appConfig.Ctx, "sendSms"+in.Mobile).Result()
		u.Password = result
		u.SAId = in.SAId

		if err = u.Register(appConfig.DB); err != nil {
			return nil, errors.New("创建账号失败！")
		}

	} else {
		return nil, errors.New("该手机号已注册过账号！")
	}

	return &__.RegisterResp{
		UserId: int64(u.ID),
	}, nil
}

func (s *Server) AddSA(_ context.Context, in *__.AddSAReq) (*__.AddSAResp, error) {
	var err error
	var sa models.SchoolArea

	sa.SchoolName = in.SchoolName
	sa.Types = in.Types
	sa.Ads = in.Ads
	if err = sa.CreateSA(appConfig.DB); err != nil {
		return nil, errors.New("校区添加失败！")
	}

	return &__.AddSAResp{
		SchoolId: int64(sa.ID),
	}, nil
}

func (s *Server) SchoolList(_ context.Context, in *__.SchoolListReq) (*__.SchoolListResp, error) {

	var sa models.SchoolArea
	var saList []*__.ListSchool

	listSA, err := sa.ListSA(appConfig.DB, in.Name, in.Status, int(in.Page), int(in.PageSize))
	if err != nil {
		return nil, err
	}

	for _, ss := range listSA {
		list := __.ListSchool{
			Id:         int64(ss.ID),
			Image:      ss.Image,
			SchoolName: ss.SchoolName,
			Types:      ss.Types,
			Ads:        ss.Ads,
			Status:     ss.Status,
		}
		saList = append(saList, &list)
	}

	return &__.SchoolListResp{
		List: saList,
	}, nil
}

func (s *Server) UserList(_ context.Context, in *__.UserListReq) (*__.UserListResp, error) {

	var us models.UserList
	var ul []*__.ListUser

	listUs, err := us.UserList(appConfig.DB, in.Mobile)
	if err != nil {
		return nil, err
	}

	for _, u := range listUs {
		list := __.ListUser{
			Mobile:     u.Mobile,
			Account:    u.Account,
			SchoolName: u.SchoolName,
		}
		ul = append(ul, &list)
	}

	return &__.UserListResp{
		List: ul,
	}, nil
}
